from flask import Flask,render_template,abort
from flask_sqlalchemy import SQLAlchemy
from pymongo import MongoClient

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/test'
db = SQLAlchemy(app)
mongobd = MongoClient('127.0.0.1',27017).test


class File(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    content = db.Column(db.Text)
    created_time = db.Column(db.DateTime)

    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category',
        backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, created_time, category, content):
        self.title = title
        self.content = content
        self.created_time = created_time
        self.category = category

    def __repr__(self):
        return '<File %r>' % self.title

    # 向文章添加标签
    def add_tag(self, tag_name):
        # 为当前文章添加 tag_name 标签存入到 MongoDB
        old = mongobd.tag.find_one({'file':self.id})
        new = []
        if old:
            old = old['tag_name']
            new = old
            if(tag_name not in old):
                new.append(tag_name) 
                mongobd.tag.update_one({'file':self.id},{"$set":{'tag_name':new}})
        else:
            new.append(tag_name)
            mongobd.tag.insert({'file':self.id,'tag_name':new})

    # 移除标签
    def remove_tag(self, tag_name):
        # 从 MongoDB 中删除当前文章的 tag_name 标签
        old = mongobd.tag.find_one({'file':self.id})
        if old:
            old = old['tag_name']
            if(tag_name in old):
                old.remove(tag_name) 
                mongobd.tag.update_one({'file':self.id},{"$set":{'tag_name':old}})

    # 标签列表
    @property
    def tags(self):
        # 读取 mongodb，返回当前文章的标签列表
        tags = mongobd.tag.find_one({'file':self.id})['tag_name']
        return tags


class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Category %r>' % self.name


@app.errorhandler(404)
def not_found(error):
    return render_template('404.html'), 404

@app.route('/')
def index():
    allCourse = File.query.all()
    return render_template('index.html', allCourse=allCourse)

@app.route('/files/<fileid>')
def file(fileid):
    course = File.query.filter_by(id = fileid).first()
    if course is None:
        abort(404) 
    else:
        return render_template('file.html', course=course)
       

if __name__ == '__main__':
    app.run()